#!/usr/bin/env python
import os
import sys
import subprocess
import urllib.request
import zipfile

def download_python():
    """下载Python安装包"""
    print("正在下载Python 3.8.10...")
    
    # Python 3.8.10 下载链接
    url = "https://www.python.org/ftp/python/3.8.10/python-3.8.10-amd64.exe"
    filename = "python-3.8.10-amd64.exe"
    
    try:
        urllib.request.urlretrieve(url, filename)
        print(f"下载完成: {filename}")
        return filename
    except Exception as e:
        print(f"下载失败: {e}")
        return None

def install_python(installer_path):
    """安装Python"""
    print("正在安装Python...")
    
    # 安装命令 - 静默安装到用户目录
    install_dir = os.path.expanduser("~\\Python38")
    cmd = f'{installer_path} /quiet InstallAllUsers=0 TargetDir={install_dir}'
    
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        if result.returncode == 0:
            print(f"Python安装成功到: {install_dir}")
            return install_dir
        else:
            print(f"安装失败: {result.stderr}")
            return None
    except Exception as e:
        print(f"安装出错: {e}")
        return None

def setup_environment(python_dir):
    """设置环境变量"""
    print("设置环境变量...")
    
    # 创建批处理文件来设置环境
    bat_content = f"""@echo off
set PYTHON_HOME={python_dir}
set PATH=%PYTHON_HOME%;%PYTHON_HOME%\\Scripts;%PATH%
echo Python环境已设置: %PYTHON_HOME%
echo 现在可以运行: python --version
cmd /k
"""
    
    with open("setup_python_env.bat", "w") as f:
        f.write(bat_content)
    
    print("环境设置文件已创建: setup_python_env.bat")

def main():
    print("=== Python手动安装工具 ===\n")
    
    # 检查是否已有Python
    try:
        result = subprocess.run(["python", "--version"], capture_output=True, text=True)
        if result.returncode == 0:
            print(f"检测到Python: {result.stdout.strip()}")
            choice = input("是否继续安装新的Python版本? (y/n): ")
            if choice.lower() != 'y':
                return
    except:
        pass
    
    # 下载Python
    installer = download_python()
    if not installer:
        print("下载失败，请手动下载Python 3.8.10")
        return
    
    # 安装Python
    python_dir = install_python(installer)
    if not python_dir:
        print("安装失败")
        return
    
    # 设置环境
    setup_environment(python_dir)
    
    print("\n安装完成！")
    print("请运行: setup_python_env.bat")
    print("然后安装Django: pip install django djangorestframework pymysql pypinyin")

if __name__ == "__main__":
    main() 